<template>
  <el-form ref="form" :model="user" :rules="rules" label-width="80px">
    <el-form-item label="用户名称" prop="realName">
      <el-input v-model="user.realName" />
    </el-form-item> 
    <el-form-item label="手机号码" prop="phonenumber">
      <el-input v-model="user.phonenumber" maxlength="11" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="user.email" maxlength="50" />
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="user.sex">
        <el-radio label="0">男</el-radio>
        <el-radio label="1">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <div class="dingding">社交账号绑定</div>
      <div style="height: 50px">
        <div
          style="width: 40px; height: 40px; position: relative"
          @mouseenter="handleMouseEnter"
          @mouseleave="handleMouseLeave"
        >
          <img
            class="dingdinglogo"
            src="https://pic2.zhimg.com/v2-20396f93f12aa357aebf0f46ec13edec_xs.jpg?source=1940ef5c"
          />
          <div class="mask" v-show="isShowMask">
            <span v-if="!dingTalkUserId" @click="binding">绑定</span>
            <span v-else @click="unBinding">解绑</span>
          </div>
          <div class="maskdefalut" v-show="!dingTalkUserId"></div>
        </div>
        <p class="dingdingtext">钉钉</p>
        <div id="user_container" class="login_container_class"></div>
      </div>
    </el-form-item>
    <el-form-item>
      <div>
        <el-button type="primary" size="mini" @click="submit">保存</el-button>
        <el-button type="danger" size="mini" @click="close">关闭</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  updateUserProfile,
  dingtalkBind,
  getUserProfile,
  dingtalkUnbind,
} from "@/api/system/user"

export default {
  props: {
    user: {
      type: Object,
    },
  },
  data() {
    return {
      // 表单校验
      rules: {
        realName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      isShowMask: false,
      dingTalkUserId: null,
      ddConfig: {
        url: "https://sys.fkmalls.com/user/profile",
        agentId: "ding8sugpunwvgg5rnjy",
      },
    }
  },
  async created() {
    const res = await getUserProfile()
    this.state = res.data.user.userId
    this.dingTalkUserId = res.data.user.dingTalkUserId
    const { authCode, state } = this.$route.query
    if ((authCode, state)) {
      window.localStorage.setItem("state", JSON.stringify(1))
      window.localStorage.setItem("authCode", JSON.stringify(authCode))
      window.close()
    }
  },
  mounted() {
    this.code = JSON.parse(window.localStorage.getItem("authCode"))
    this.state = JSON.parse(window.localStorage.getItem("state"))
  },
  methods: {
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateUserProfile(this.user).then((response) => {
            this.msgSuccess("修改成功")
          })
        }
      })
    },
    close() {
      this.$store.dispatch("tagsView/delView", this.$route)
      this.$router.push({ path: "/index" })
    },
    handleMouseEnter() {
      this.isShowMask = true
    },
    handleMouseLeave() {
      this.isShowMask = false
    },
    binding() {
      const { agentId, url } = this.ddConfig
      const cloneUrl = encodeURIComponent(url)
      const windowFeatures = "width=1000,height=800,resizable=yes"
      const hrefUrl = `https://login.dingtalk.com/oauth2/auth?redirect_uri=${cloneUrl}&response_type=code&client_id=${agentId}&scope=openid&state=${this.state}&prompt=consent`
      const childWindow = window.open(hrefUrl, "_blank", windowFeatures)
      let loop = setInterval(() => {
        if (childWindow.closed) {
          clearInterval(loop)
          const code = JSON.parse(window.localStorage.getItem("authCode"))
          const state = JSON.parse(window.localStorage.getItem("state"))
          if (state) {
            this.handleCodeBinding(code, this.state)
            window.localStorage.removeItem("state")
          }
        }
      }, 800)
    },
    unBinding() {
      this.$confirm("您确定要解除绑定吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          dingtalkUnbind({
            userId: this.state,
          }).then((res) => {
            this.dingTalkUserId = null
            this.$message({
              type: "success",
              message: "解绑成功!",
            })
          })
        })
        .catch(() => {})
    },
    async handleCodeBinding(code, state) {
      await dingtalkBind({
        state,
        code,
      })
      const res = await getUserProfile()
      this.dingTalkUserId = res.data.user.dingTalkUserId
      this.msgSuccess("绑定成功")
    },
  },
}
</script>
<style scoped>
.dingding {
  font-size: 14px;
  color: #606266;
  font-weight: 600;
  position: relative;
  left: -80px;
}
.dingdinglogo {
  width: 40px;
  height: 40px;
}
.dingdingtext {
  padding: 0;
  margin: 0;
  padding-left: 7px;
  margin-bottom: 10px;
}
.list {
  height: 50px;
}
.mask {
  position: absolute;
  z-index: 666;
  width: 35px;
  height: 35px;
  border-radius: 50%;
  background-color: #000;
  opacity: 0.5;
  top: 2px;
  left: 2px;
}
.maskdefalut {
  position: absolute;
  width: 35px;
  height: 35px;
  border-radius: 50%;
  background-color: #eee;
  opacity: 0.7;
  top: 2px;
  left: 2px;
}
.mask span {
  color: #fff;
  position: relative;
  top: 2px;
  left: 7px;
  cursor: auto;
  font-size: 12px;
}
.unBinding {
  position: relative;
  top: -105px;
  left: 8px;
  font-size: 12px;
  color: #000;
}
</style>
